package com.taxt.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.gyf.immersionbar.ImmersionBar;
import com.hjq.bar.TitleBar;
import com.hjq.base.BaseAdapter;
import com.hjq.base.FragmentPagerAdapter;
import com.hjq.http.EasyConfig;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.taxt.R;
import com.taxt.aop.SingleClick;
import com.taxt.app.AppFragment;
import com.taxt.app.TitleBarFragment;
import com.taxt.http.api.HomeDataApi;
import com.taxt.http.api.LoginApi;
import com.taxt.http.glide.GlideApp;
import com.taxt.http.model.HomeInfoBean;
import com.taxt.http.model.HttpData;
import com.taxt.http.model.PersonInfoBean;
import com.taxt.other.MD5Utils;
import com.taxt.other.SpUtils;
import com.taxt.ui.activity.DeclareDataActivity;
import com.taxt.ui.activity.HomeActivity;
import com.taxt.ui.activity.LoginActivity;
import com.taxt.ui.activity.PersonalBaseDataActivity;
import com.taxt.ui.activity.PersonalJobDataActivity;
import com.taxt.ui.activity.SearchDataActivity;
import com.taxt.ui.adapter.HotPBusinessAdapter;
import com.taxt.ui.adapter.HotProblemAdapter;
import com.taxt.ui.adapter.TabAdapter;
import com.taxt.widget.XCollapsingToolbarLayout;
import com.xj.marqueeview.MarqueeView;
import com.xj.marqueeview.base.CommonAdapter;
import com.xj.marqueeview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.bgabanner.BGABanner;
import okhttp3.Call;

/**
 * author : wq
 * <p>
 * time   : 2018/10/18
 * desc   : 首页 Fragment
 */
public final class HomeFragment extends TitleBarFragment<HomeActivity> implements OnRefreshListener {

    private TitleBar mToolbar;
    private BGABanner mBgaBanner;
    private TextView mHintView;
    private MarqueeView marqueeView;
    private AppCompatImageView mSearchView;
    private AppCompatImageView mHotImg;
    private RecyclerView mTabView;
    private RelativeLayout showHotTips;
    private SmartRefreshLayout smartRefreshLayout;
    private RecyclerView mHotProblemRcv,mHotBusinessRcv;
    HotProblemAdapter hotProblemAdapter;
    HotPBusinessAdapter hotPBusinessAdapter;
    private NestedScrollView msScrollView;
    int mAlpha;
    private List<HomeInfoBean.CommonBusinessDTO>list=new ArrayList<>();
    private List<String>hotList=new ArrayList<>();
    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_fragment;
    }

    @Override
    protected void initView() {

        mToolbar = findViewById(R.id.tb_home_title);
        mBgaBanner= findViewById(R.id.banner_guide_content);
        mHotImg = findViewById(R.id.hot_img);
        marqueeView = findViewById(R.id.marqueeView);
        mHintView = findViewById(R.id.tv_home_hint);
        mSearchView = findViewById(R.id.iv_home_search);
        mHotProblemRcv = findViewById(R.id.hot_rcv);
        mHotBusinessRcv=findViewById(R.id.business_rcv);
        msScrollView=findViewById(R.id.scroll_view);
        showHotTips=findViewById(R.id.showHotTips);
        smartRefreshLayout=findViewById(R.id.refreshLayout);
        hotProblemAdapter=new HotProblemAdapter(getContext());
        mHotProblemRcv.setAdapter(hotProblemAdapter);
        mHotProblemRcv.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false));
        smartRefreshLayout.setOnRefreshListener(this);
        hotPBusinessAdapter=new HotPBusinessAdapter(getContext(),list);
        hotPBusinessAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                if(position==2){
                    startActivity(DeclareDataActivity.class);
                }
            }
        });
        mHotBusinessRcv.setAdapter(hotPBusinessAdapter);
        mHotBusinessRcv.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false));
        setOnClickListener(R.id.search_btn);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initData() {
        scrollViewListener();
        if(!(SpUtils.decodeParcelable("home",HomeInfoBean.class)==null||SpUtils.decodeParcelable("home",HomeInfoBean.class).equals(""))){
            HomeInfoBean personInfoBean = (HomeInfoBean) SpUtils.decodeParcelable("home", HomeInfoBean.class);
            showHomeData(personInfoBean);
        }else {
            getHomeData(1);
        }
    }





    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void getHomeData(int flag) {
        smartRefreshLayout.finishRefresh(2000/*,false*/);
        EasyHttp.post(this)
                .api(new HomeDataApi()
                )
                .request(new HttpCallback<HttpData<HomeInfoBean>>(this) {

                    @Override
                    public void onStart(Call call) {
                        if(flag==1) {
                            showDialog();
                        }
                    }

                    @Override
                    public void onEnd(Call call) {
                        hideDialog();
                    }

                    @Override
                    public void onSucceed(HttpData<HomeInfoBean> data) {
                        hideDialog();
                        if (data.getData() != null) {
                            SpUtils.encodeParcelable("home",data.getData());
                            showHomeData(data.getData());
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        hideDialog();
                    }
                });
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.search_btn) {
            startActivity(SearchDataActivity.class);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void scrollViewListener(){
        msScrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View view, int i, int i1, int i2, int i3) {
                int minHeight = 50;
                int maxHeight = mToolbar.getHeight() - 25;
                // 滑动距离小于定义得最小距离
                if (msScrollView.getScrollY() <= minHeight) {
                    mAlpha = 0;
                }
                // 滑动距离大于定义得最大距离
                else if (msScrollView.getScrollY() > maxHeight) {
                    mAlpha = 255;
                }
                // 滑动距离处于最小和最大距离之间
                else {
                    // （滑动距离 - 开始变化距离）：最大限制距离 = mAlpha ：255
                    mAlpha = (msScrollView.getScrollY() - minHeight) * 255 / (maxHeight - minHeight);
                }

                // 初始状态 标题栏/导航栏透明等
                if (mAlpha <= 0) {
                    setViewBackgroundAlpha(mToolbar, mAlpha);
                }
                //  终止状态：标题栏/导航栏 不在进行变化
                else if (mAlpha >= 255) {
                    setViewBackgroundAlpha(mToolbar, mAlpha);

                }
                // 变化中状态：标题栏/导航栏随ScrollView 的滑动而产生相应变化
                else {
                    setViewBackgroundAlpha(mToolbar, mAlpha);
                }
            }
        });
    }

    /**
     * 设置View的背景透明度
     *
     * @param view
     * @param alpha
     */
    public void setViewBackgroundAlpha(View view, int alpha) {
        if (view == null) return;
        if(alpha<=0) {
            view.setBackgroundColor(getColor(R.color.transparent));
        }else{
            view.setBackground(getDrawable(R.drawable.home_title_bg));
        }
    }

    public void showHomeData(HomeInfoBean bean){
        GlideApp.with(getContext())
                .load(bean.getHotImageAddress())
                .into(mHotImg);
        if(bean.getHotImageTitleFlag()!=null){
            if(bean.getHotImageTitleFlag().equals("0")){
                showHotTips.setVisibility(View.GONE);
            }else{
                showHotTips.setVisibility(View.VISIBLE);
            }
        }
        SpUtils.encode("showIcon",bean.getIsShowIcon001Flag());
        if(bean.getBannerUrlAddress()!=null){
            mBgaBanner.setAutoPlayAble(bean.getBannerUrlAddress().size() > 1);
            mBgaBanner.setAdapter(new BGABanner.Adapter<ImageView, String>() {
                @Override
                public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {

                    GlideApp.with(getContext())
                            .load(model)
                            .into(itemView);
                }
            });
            mBgaBanner.setData(bean.getBannerUrlAddress(),null);
        }
        if (bean.getHotProblem() != null) {
            hotProblemAdapter.setData(bean.getHotProblem());
        }
        if(bean.getCommonBusiness()!=null){
            list.clear();
            list.addAll(bean.getCommonBusiness());
            hotPBusinessAdapter.setData(list);
        }
        if (bean.getMessageTitle() != null) {

            SimpleTextAdapter simpleTextAdapter = new SimpleTextAdapter(getActivity(), bean.getMessageTitle());
            marqueeView.setAdapter(simpleTextAdapter);
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        getHomeData(2);
    }

    public class SimpleTextAdapter extends CommonAdapter<String> {

        public SimpleTextAdapter(Context context, List<String> datas) {
            super(context, R.layout.item_simple_text, datas);
        }

        @Override
        protected void convert(ViewHolder viewHolder, String item, int position) {
            TextView tv = viewHolder.getView(R.id.marqueeTextView);
            tv.setText(item);
        }

    }

}